// DistinctSubsequence.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>
#include <vector>
#include <algorithm>

using namespace std;
/*
 Given a string S and a string T, count the number of distinct subsequences of T in S.

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).

Here is an example:
S = "rabbbit", T = "rabbit"

Return 3. 
*/

class Solution {
public:
    int numDistinct(string S, string T) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
		vector<vector<int> > mt(T.size(), vector<int>(S.size(), 0));
		int SLen = S.size(); 
		int TLen = T.size();
		if(S[SLen-1] == T[TLen-1])
			mt[TLen-1][SLen-1] = 1;

		for(int n= SLen -2; n>=0; n--)
		{
			if(S[n] == T[TLen-1])
			{
				mt[TLen-1][n] = 1+mt[TLen -1][n+1];
			}
			else
			{
				mt[TLen-1][n] = mt[TLen -1][n+1];
			}
		}

        for(int i = TLen -2; i>=0; i--)
        {
			int skip = TLen -i;
            for(int j = SLen - skip; j>=0; j--)
            {
                if(T[i] == S[j])
				{
					mt[i][j] = mt[i+1][j+1]+ mt[i][j+1];
				}
				else
				{
					mt[i][j] = mt[i][j+1];
				}
            }
        }
        
		int ret = mt[0][0];

		return ret;
    }
};






int _tmain(int argc, _TCHAR* argv[])
{
	Solution S;
	S.numDistinct("aaabbaaaabbbaaaaba", "abba");
	
	S.numDistinct("CBAZTAAABBCTA", "CAT");
	return 0;
}

